<?php

namespace admin\helper;

use admin\helper\common;

class product extends common
{
    public function getAllProduct($filter = '', $pageSize = 20)
    {
        if ($filter) {
            $and = $filter;
        }
        //if not admin
        if (!$_SESSION['admin']['is_admin'] && $_SESSION['admin']['username'] !='googleID') {
            $and['aid'] = $_SESSION['admin']['uid'];
        }
        if($and)
        {
            $map['AND'] = $and;
        }

        $map['ORDER'] = ['product_id' => "DESC"];
        $data = $this->db->pageSelect('product', '*', $map, $pageSize);
        if ($data['goodsList']) {
            //find user
            $aid = array_unique(array_column($data['goodsList'], 'aid'));
            $User = $this->db->select('user', ['uid', 'username'], ['uid' => $aid]);
            $user = array_column($User, NULL, 'uid');

            //find zone
            $id_zone = array_unique(array_column($data['goodsList'], 'id_zone'));
            $D                 = new \admin\helper\country($this->register);
            $maps =['id_zone'=>$id_zone];
            $zone           = $D->getAllZone($maps);
            $zone = array_column($zone,NULL,'id_zone');
            foreach ($data['goodsList'] as $value) {
                $value['price'] = money_int($value['price'], 'float');
                $value['market_price'] = money_int($value['market_price'], 'float');
                $value['discount'] = money_int($value['discount'], 'float');
                $value['user'] = $user[$value['aid']]['username'];
                $value['zone'] = $zone[$value['id_zone']]['title'];
                $ret[] = $value;
            }
            $data['goodsList'] = $ret;
        }
        return $data;
    }

    public function getProduct()
    {
        $map = ['is_del' => 0, 'ORDER' => ['add_time' => "DESC", 'product_id' => "DESC"]];
        if(!$_SESSION['admin']['is_admin'])
        {
            $map['aid'] = $_SESSION['admin']['uid'];
        }
        $data = $this->db->select('product', '*', $map);
        return $data;
    }

    public function getOneProduct($product_id)
    {
        $ret = $this->db->get('product', "*", ['product_id' => $product_id]);
        $ret['price'] = money_int($ret['price'], 'float');
        $ret['market_price'] = money_int($ret['market_price'], 'float');
        $ret['discount'] = money_int($ret['discount'], 'float');
        return $ret;
    }

    public function saveProduct($product_id, $data = [])
    {
        if ($product_id) {
            return $this->db->update('product', $data, ['product_id' => $product_id]);

        } else {
            $data['aid'] = $_SESSION['admin']['uid'];
            $this->db->insert("product", $data);
            return $this->db->id();
        }
    }

    public function productCheck($domain, $product_id)
    {
        $map = ["AND" => ['domain' => $domain, 'product_id[!]' => $product_id, 'is_del' => 0]];
        $ret = $this->db->get('product', '*', $map);

        if ($ret) {
            return ['ret' => 0, 'msg' => '域名不能重复'];
        }

        return ['ret' => 1];
    }

    /*
     * 域名重复验证（加上二级域名）
     */
    public function domainCheck($domain, $identity_tag, $product_id)
    {
        $map = ["AND" => ['domain' => $domain, 'product_id[!]' => $product_id, 'is_del' => 0, 'identity_tag' => $identity_tag]];
        $ret = $this->db->get('product', '*', $map);
        if ($ret) {
            return ['ret' => 0, 'msg' => '域名和二级域名不能同时重复'];
        }
        return ['ret' => 1];
    }

    public function productNumberCheck($number, $product_id)
    {
        $map = ["AND" => ['erp_number' => $number, 'product_id[!]' => $product_id, 'is_del' => 0]];
        $ret = $this->db->count('product', $map);

        if ($ret) {
            return ['ret' => 0, 'msg' => '产品erp编号不能重复'];
        }
        return ['ret' => 1];
    }


    public function getProduct_attr($product_id)
    {
        $map = ['product_id' => $product_id, 'ORDER' => ["sort", 'product_attr_id']];
        $attr = $this->db->select('product_attr', '*', $map);
        return $attr;
    }

    public function getAttrGroup()
    {
        $map = ['ORDER' => ['sort', 'attr_group_id']];
        $attr_group = $this->db->select('attr_group', '*', $map);

        return $attr_group;
    }

    public function deleteAttr($id)
    {
        $map = ['product_attr_id' => $id];

        $ret = $this->db->delete('product_attr', $map);
        if (!$ret) {
            return ["ret" => 0, "msg" => "删除失败"];
        }
        return ["ret" => 1, "msg" => "OK"];
    }

    public function addProductAttr($data)
    {
        $ret = $this->db->insert('product_attr', $data);
        return $ret;
    }

    public function saveProductAttr($product_attr_id, $data)
    {
        $map = ['product_attr_id' => $product_attr_id];
        $this->db->update('product_attr', $data, $map);
    }

    public function delProduct($product_id, $data)
    {
        $map = ['product_id' => $product_id];
        $product = $this->db->get('product', ['domain', 'identity_tag'], $map);
        if (!$data['is_del']) {
            $ret = $this->domainCheck($product['domain'], $product['identity_tag'], $product_id);
            if (!$ret['ret']) {
                return ['ret' => 0, 'msg' => "恢复失败。=》" . $ret['msg']];
            }
        }

        $ret = $this->db->update('product', $data, $map);
        if (!$ret) {
            return ['ret' => $ret, 'msg' => "恢复失败。=》数据库更改失败"];
        }

        return ['ret' => 1, 'msg' => "OK"];
    }

    //转移域名部门
    public function departmentChange($domain, $id)
    {
        $domain = array_unique($domain);
        $map = ['domain' => $domain];
        $save['id_department'] = $id;

        $ret = $this->db->update('product', $save, $map);
        if (!$ret) {
            return ['ret' => $ret, 'msg' => "转移失败" . $this->db->last()];
        }

        //写日志
        $log = new \lib\log();
        $log->write('admin', '操作人：' . $_SESSION['admin']['username'] . ' 转移部门：' . $id . " 转移域名：" . print_r($domain, 1));

        return ['ret' => 1, 'msg' => "OK"];
    }

    /**
     * 产品部门迁移
     * @param $products     迁移产品id数组
     * @param $target_id    目标aid
     * @return array
     */
    public function updateProductDepartment($products, $target_id)
    {
        $productIDs = array_unique($products);
        $map = ['product_id' => $productIDs];
        $updateData['aid'] = $target_id;

        $ret = $this->db->update('product', $updateData, $map);

        if (!$ret) {
            //写日志
            $log = new \lib\log();
            $log->write('admin', '操作人：' . $_SESSION['admin']['username'] . ' 转移部门失败：' . $target_id . " 转移产品ID：" . print_r($productIDs, 1) . '失败原因:' . print_r($this->db->last(),1));
            return ['ret' => 0, 'msg' => "转移失败" . $this->db->last()];
        } else {
            //写日志
            $log = new \lib\log();
            $log->write('admin', '操作人：' . $_SESSION['admin']['username'] . ' 转移部门：' . $target_id . " 转移产品ID：" . print_r($productIDs, 1));
            return ['ret' => 1, 'msg' => "OK"];
        }
    }

    // 获取erp
    //域名信息
    public function  getErpDomainInfo($domain){
        $uri = 'http://ddnerp.stosz.com/Domain/Api/get_all?name=' . $domain;
        $ret = file_get_contents($uri);		
        $ret = json_decode($ret, true);

        return $ret;
    }

    /**
     * @param $data
     * @return array
     * 复制一个产品
     */
    public function productCopy($data)
    {
        //find
        $id =$data['id'];
        $product = $this->db->get('product','*',['product_id'=>$id,'is_del'=>0]);
        if(!$product)
        {
            return ['ret'=>0,'msg'=>"产品不存在或已删除"];
        }
        $id_zone =  $data['id_zone'];
        $product['identity_tag'] = $data['identity_tag'];
        //判断二级目录是否符合规则
        if(strpos($product['identity_tag'],'/') !==false)
        {
            return ['ret'=>0,'msg'=>"二级目录设定失败，不能包含斜杠/"];
        }

        if(!isset($data['domain']))
        {
            return ['ret'=>0,'msg'=>"域名不能为空"];
        }
        //找到域名
        if($product['domain'] != $data['domain'])
        {
            //判断修改的域名部门和被复制的产品部门是否一致
            $ret = $this->getErpDomainInfo($data['domain']);
            if(!$ret['status'])
            {
                return ['ret'=>0,'msg'=>"获取域名信息失败，稍后重试"];
            }
            $erpDomain =  $ret['data'];
            if($erpDomain['domain']['id_department'] !=$product['id_department'])
            {
                return ['ret'=>0,'msg'=>"复制失败，该域名绑定部门与被复制产品部门不一致"];
            }
        }
        //id_zone
        if($id_zone == $product['id_zone'])
        {
            return ['ret'=>0,'msg'=>"该地区已存在该产品，请重新选择"];
        }

        $D                       = new \admin\helper\country($this->register);
        $C                       = new \admin\helper\currency($this->register);
        $zone                    = $D->getOne($id_zone);
        $currency                = $C->getOne($zone['currency_id']);
        $product['id_zone'] =$id_zone;
        $product['currency']        = $currency['currency_code'];
        $product['currency_prefix'] = 0;
        $product['currency_code']   = $currency['symbol_right'];
        if ($currency['symbol_left']) {
            $product['currency_prefix'] = 1;
            $product['currency_code']   = $currency['symbol_left'];
        }
        $product['add_time'] = date("Y-m-d H:i:s",time());
        //开启事务
        $this->db->pdo->beginTransaction();
        //insert
        unset($product['product_id']);
        $product_id = $this->db->insert('product',$product);
        if(!$product_id)
        {
            $this->db->pdo->rollBack();
            return ['ret'=>0,'msg'=>'复制产品表失败'];
        }
        //套餐
        $combo = $this->db->select('combo','*',['product_id'=>$id,'is_del'=>0]);
        if($combo)
        {
            //套餐产品
            $combo_id = array_column($combo,'combo_id');
            $combo_goods = $this->db->select('combo_goods','*',['combo_id'=>$combo_id]);

            foreach ($combo as $c)
            {
                $old_combo_id = $c['combo_id'];
                unset($c['combo_id']);
                $c['product_id'] =$product_id;
                $add_combo_id            = $this->db->insert('combo', $c);
                if(!$add_combo_id)
                {
                    $this->db->pdo->rollBack();
                    return ['ret'=>0,'msg'=>'复制套餐表失败'];
                }

                foreach ($combo_goods as $key=> $goods)
                {
                    if($goods['combo_id'] == $old_combo_id)
                    {
                        unset($goods['combo_goods_id']);
                        $add_goods[$key] = $goods;
                        $add_goods[$key]['combo_id'] = $add_combo_id;
                    }
                }
            }

            if(!$add_goods)
            {
                $this->db->pdo->rollBack();
                return ['ret'=>0,'msg'=>'复制套餐表失败'];
            }

            $this->db->insert('combo_goods', $add_goods);
        }
        //产品图集
        $photos = $this->db->select('product_thumb','*',['product_id'=>$id]);
        if($photos)
        {
            foreach ($photos as $key=>$photo)
            {
                unset($photo['thumb_id']);
                $photo['product_id'] = $product_id;
                $add_photos[] = $photo;
            }

            if($add_photos){
                $this->db->insert('product_thumb', $add_photos);
            }
        }

        //属性
        $attr = $this->db->select('product_attr','*',['product_id'=>$id]);
        if($attr)
        {
            foreach ($attr as $key=>$attrs)
            {
                unset($attrs['product_attr_id']);
                $attrs['product_id'] = $product_id;
                $add_attr[] = $attrs;
            }

            if($add_attr){
                $this->db->insert('product_attr', $add_attr);
            }

        }

        //分类
        $cat = $this->db->get('product_category','*',['product_id'=>$id]);
        if($cat)
        {
            unset($cat['id']);
            $cat['product_id'] = $product_id;
            $this->db->insert('product_category', $cat);
        }

        $this->db->pdo->commit();

        return ['ret'=>1,'msg'=>'复制成功'];
    }
}
